﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using System.Text.RegularExpressions;
using System.DirectoryServices.AccountManagement;

namespace CodePlex.TfsPluginSuite.Helper
{
    public class TfsHelper
    {    
        private TeamFoundationRequestContext requestContext;

        public TfsHelper(TeamFoundationRequestContext requestContext)
        {
            this.requestContext = requestContext;
        }

        public NodeInfo GetIterationInfo(int workItemId)
        {
            TfsTeamProjectCollection tpc = GetTeamProjectCollection();
            ICommonStructureService css = (ICommonStructureService)tpc.GetService(typeof(ICommonStructureService));
            var workItemStore = GetWorkItemStore();
            var workItem = workItemStore.GetWorkItem(workItemId);
            Node iterationNode = workItemStore.Projects.GetById(workItem.Project.Id).FindNodeInSubTree(workItem.IterationId);
            return css.GetNode(iterationNode.Uri.ToString());
        }

        public WorkItemStore GetWorkItemStore()
        {
            var uri = GetTFSUri();
            var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
            return tpc.GetService<WorkItemStore>();
        }

        private TfsTeamProjectCollection GetTeamProjectCollection()
        {
            return new TfsTeamProjectCollection(GetTFSUri());
        }

        private Uri GetTFSUri()
        {
            var locationService = this.requestContext.GetService<TeamFoundationLocationService>();
            return new Uri(locationService.GetServerAccessMapping(requestContext).AccessPoint + "/" + requestContext.ServiceHost.Name);
        }

    }
}
